var mixer = mixer || {};


mixer.workspace = function() {
  var ws = function() {
    var self = {};

    self.model = function() {
      var model = {};

      model.root = {};
      model.context = model.root;

      model.on = function(eventType, handler) {
        jQuery(document).on(eventType, handler);
      };
      model.emit = function(eventType, detail) {
        jQuery(document).trigger(eventType, detail);
      };

      model.addColumn = function(spec) {
        var coldetail = {};
        coldetail.colname = spec.propname;
        model.emit("newcolumn", coldetail);

        

        console.log("ADDCOL: " + jQuery(spec.column).length);

        jQuery(spec.column).css({"font-style": "italic", fontStyle: "italic", opacity:0.5});
      };



      return model;
    }();

    self.view = function() {
      var view = {};

      view.state = {};
      
      view.listenerQueue = [];

      view.setContainer = function(container) {
        view.state.container = container;

        view.listenerQueue.forEach(function(spec) {
          view.on(spec.eventType, spec.handler);
        });
      };

      view.addColumn = function(event, spec) {
        jQuery(view.state.container).css({background: "white"});
        
        var head0 = jQuery("#head0");
        jQuery(view.state.container).find("tr.header-row").each(function(row) {
          var copy = jQuery(head0).clone();
          copy.text(spec.colname || "COLUMN");
          copy.attr("id", "");
          copy.attr("rowspan", "1");
          copy.appendTo(jQuery(this));
        });
        var cell0 = jQuery("#cell0");
        jQuery(view.state.container).find("tr.mixer-row").each(function(row) {
          var copy = jQuery(cell0).clone();
          copy.text("");
          copy.attr("id", "");
          copy.attr("rowspan", "1");
          copy.appendTo(jQuery(this));
        });

        
      };

      view.on = function(eventType, handler) {
        if (view.state.container) {
          jQuery(view.state.container).on(eventType, handler);
          return;
        }

        view.listenerQueue.push({eventType:eventType, handler:handler});
      };
      view.emit = function(eventType, detail) {
        console.log("EMIT: %s %j", eventType, detail);
        jQuery(view.state.container).trigger(eventType);
      };

      view.on("barbaz", function() {
        console.log("barbaz!");
      });

      return view;
    }();

    self.model.on('newcolumn', self.view.addColumn);

    return self;
  };
  ws.ok = 2;

  return ws;
}();
